package org.jim.server.command.handler;

import org.jim.common.ImAio;
import org.jim.common.ImConst;
import org.jim.common.ImPacket;
import org.jim.common.ImStatus;
import org.jim.common.cache.redis.RedisCache;
import org.jim.common.cache.redis.RedisCacheManager;
import org.jim.common.packets.BannedBody;
import org.jim.common.packets.Command;
import org.jim.common.packets.RespBody;
import org.jim.common.utils.ImKit;
import org.jim.common.utils.JsonKit;
import org.jim.server.command.AbstractCmdHandler;
import org.tio.core.ChannelContext;

public class BannedStateReqHandler extends AbstractCmdHandler {

    @Override
    public ImPacket handler(ImPacket packet, ChannelContext channelContext) throws Exception {
        BannedBody bannedBody = null;
        try {
            bannedBody = JsonKit.toBean(packet.getBody(), BannedBody.class);
        } catch (Exception e) {
            //禁言状态请求消息格式不正确
            return ImKit.ConvertRespPacket(new RespBody(Command.COMMAND_BANNEDSTATE_RESP, ImStatus.C10022), channelContext);
        }
        String userId = bannedBody.getFrom();
        String groupId = bannedBody.getGroupId();

        RedisCache groupCache = RedisCacheManager.getCache(ImConst.GROUP);
        Integer bannedInd = groupCache.get(groupId + ":setting:banned", Integer.class);
        if (bannedInd == null) {
            bannedInd = 0;
        }
        bannedBody.setBannedInd(bannedInd);
        RespBody resPacket;
        if (bannedBody.getBannedInd().equals(1)) { // 该群是禁言状态
            resPacket = new RespBody(Command.COMMAND_BANNED_RESP, ImStatus.C10044);
        } else {
            resPacket = new RespBody(Command.COMMAND_BANNED_RESP, ImStatus.C10039);
        }
        resPacket.setData(bannedBody);
//        System.out.println(bannedBody.toJsonString());
        return ImKit.ConvertRespPacket(resPacket, channelContext);
    }

    @Override
    public Command command() {
        return Command.COMMAND_BANNEDSTATE_REQ;
    }
}
